package com.aispeech.asr.webase.controller;

import com.aispeech.asr.comm.data.vo.Result;
import com.aispeech.asr.comm.enums.APICode;
import com.aispeech.asr.comm.enums.ErrorCode;
import com.aispeech.asr.comm.exceptions.AsrException;
import com.aispeech.asr.comm.exceptions.HealthzException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ServerWebInputException;

@RestControllerAdvice
@Slf4j
public class GlobalAdvice {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.OK)
    public Result handleException(Exception ex) {
        log.warn("handle exception:", ex);
        return Result.fail(APICode.INTERNAL_ERROR);
    }

    @ExceptionHandler(HealthzException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result handleException(HealthzException ex) {
        log.warn("handle HealthzException:", ex);
        return Result.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
    }

    @ExceptionHandler(AsrException.class)
    @ResponseStatus(code = HttpStatus.OK)
    public Result handleException(AsrException ex) {
        log.warn(String.format("handle AsrException: %s(%s)", ex.getMessage(), ex.getCode()), ex);
        return Result.fail(ex.getCode(), ex.getMessage().split("\n")[0], ex.getData());
    }

    @ExceptionHandler(ServerWebInputException.class)
    @ResponseStatus(code = HttpStatus.OK)
    public Result handleException(ServerWebInputException ex) {
        log.warn("ServerWebInputException: {}", ex.getReason());
        return Result.fail(ErrorCode.ERR_PARAMS_MISSED.errid, ex.getReason());
    }
}
